package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import myBeans.NewsInfo;

public class NewsRepository {

	private Connection conn;
	
	public NewsRepository() throws NamingException, SQLException {
		InitialContext context = new InitialContext();
		DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/sharewithme");
		
		this.conn = ds.getConnection();
		
	}
	
	public boolean AddNews(NewsInfo news){
		if(news == null) return false;
		
		String contentType = "";
		byte[] attachfile = null;
		
		if(news.getNewsAttachFile() != null){
			contentType = news.getNewsAttachFile().getContentType();
			attachfile = news.getNewsAttachFile().get();
		}
		
		String sql = "INSERT INTO TBInformation(title,detail,attachimage,"
					+ "attachcontenttype,createby,createdate)"
					+ "VALUES(?,?,?,?,?,NOW())";
		
		
		try {
			//Statement stm = conn.createStatement();
			PreparedStatement preStm = conn.prepareStatement(sql);
			
			preStm.setString(1, news.getNewsTitle());
			preStm.setString(2, news.getNewsDetail());
			preStm.setBytes(3, attachfile);
			preStm.setString(4, contentType);
			preStm.setString(5,"tt@useremail.com");
			
			int result = preStm.executeUpdate();
			 
			if(result > 0)
				return true;
			else
				return false;
			
		} catch (SQLException e) {
			e.printStackTrace();
		}		
		
		return false;
	}

	public NewsInfo GetNewsById(String newsId) {
		String sql = "Select * From TBInformation where id=" + newsId;
		
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			
			if(rs.next()){
				NewsInfo news = new NewsInfo();
				
				news.setNewsTitle(rs.getString("title"));
				news.setNewsDetail(rs.getString("detail"));
				news.setNewsId(rs.getInt("id"));
				news.setNewsAttatchImage(rs.getBlob("attachimage"));
				news.setNewsAttatchContentType(rs.getString("attachcontenttype"));
				
				
				return news;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		
		return null;
	}
	
	public boolean UpdateViewCount(String newsId) {
		String sql = "update TBInformation set viewcount = viewcount + 1 where id=" + newsId;
		
		try {
			Statement stmt = conn.createStatement();
			int rowEffect = stmt.executeUpdate(sql);
			
			if(rowEffect > 0){
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		
		return false;
	}
	
}
